package com.cmzj21.springcloud.service.impl;

import cn.hutool.core.util.IdUtil;
import com.cmzj21.springcloud.service.PaymentService;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import com.netflix.hystrix.contrib.javanica.conf.HystrixPropertiesManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PathVariable;

import java.util.concurrent.TimeUnit;

/**
 * @author cmzj21
 */
@Service
@Slf4j
public class PaymentServiceImpl implements PaymentService {
    @Override
    public String paymentInfoOk(Integer id){
        return "线程池：" + Thread.currentThread().getName() + "paymentInfo_OK, id = " + id;
    }

    @HystrixCommand(fallbackMethod = "paymentInfoFailedFallback", commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "4000")
    })
    @Override
    public String paymentInfoFailed(Integer id){
        log.info("进入到方法中了");
        try {
            TimeUnit.SECONDS.sleep(3);
            log.info("睡眠过程成功完成");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "线程池：" + Thread.currentThread().getName() + "paymentInfo_Failed, id = " + id;
    }

    /**
     * 服务降级调用的服务
     * @param id 输入
     * @return 字符串
     */
    private String paymentInfoFailedFallback(Integer id){
        return "线程池：" + Thread.currentThread().getName() + "paymentInfo_Failed, o(╥﹏╥)o" + id;
    }

    /**
     * 服务熔断
     * @param id 输入
     * @return 返回结果
     */

    @Override
    @HystrixCommand(fallbackMethod = "paymentCircuitBreakerFallback", commandProperties = {
            //是否开启断路器
            @HystrixProperty(name = HystrixPropertiesManager.CIRCUIT_BREAKER_ENABLED, value = "true"),
            //请求次数
            @HystrixProperty(name = HystrixPropertiesManager.CIRCUIT_BREAKER_REQUEST_VOLUME_THRESHOLD, value = "10"),
            //时间窗口期
            @HystrixProperty(name = HystrixPropertiesManager.CIRCUIT_BREAKER_SLEEP_WINDOW_IN_MILLISECONDS, value = "10000"),
            //失败率达多少后跳闸
            @HystrixProperty(name = HystrixPropertiesManager.CIRCUIT_BREAKER_ERROR_THRESHOLD_PERCENTAGE, value = "60")
    })
    public String paymentCircuitBreaker(Integer id){
        if(id < 0){
            throw  new RuntimeException("*********id不能为负数");
        }
        String serialNumber = IdUtil.simpleUUID();
        return Thread.currentThread().getName() + "\t" + "调用成功，流水号：" + serialNumber;
    }
    public String paymentCircuitBreakerFallback(Integer id){
        return "id不能为负数，请稍后再试-----------------    id：" + id;
    }
}
